import sys
sys.path.append("./")
from api import *
import ast
import inspect
import traceback

import ast, re, sys
from xml.dom import minidom

try:
    from xml.etree import cElementTree as etree
except:
    try:
        from lxml import etree
    except:
        from xml.etree import ElementTree as etree

def prettify(xml_string):
    reparsed = minidom.parseString(xml_string)
    return reparsed.toprettyxml(indent="  ") 

class ast2xml(ast.NodeVisitor):
    def __init__(self):
        super(ast.NodeVisitor, self).__init__()
        self.path = []
        self.root = etree.Element('ast')
        self.celement = self.root
        self.lname = 'module'
    def convert(self, tree):
        self.visit(tree)
        return etree.tostring(self.root)
    def generic_visit(self, node):
        self.path.append(type(node).__name__)
        ocelement = self.celement
        self.celement = etree.SubElement(self.celement, self.lname)
        self.celement.attrib.update({'_name': type(node).__name__})
        olname = self.lname
        self.lname = type(node).__name__
        for item in node.__dict__:
            self.lname = item
            if isinstance(getattr(node, item), ast.AST):
                self.generic_visit(getattr(node, item))
            elif isinstance(getattr(node, item), list):
                ocel2 = self.celement
                olname2 = self.lname
                self.celement = etree.SubElement(self.celement, self.lname)
                self.celement.attrib.update({'_name': '_list'})
                self.lname = '_list_element'
                [self.generic_visit(childnode) for childnode in getattr(node, item) if isinstance(childnode, (ast.AST, list))]
                self.celement = ocel2
                self.lname = olname2
            else:
                self.celement.attrib.update({item: str(getattr(node, item))})
        self.path.pop()
        self.celement = ocelement
        self.lname = olname
def test():
    pass

def rule(z):
    target=Http()
    s="123"
    target.SIP=str(s)
    if target.SIP == "1.2.3.4":
        ALLOW
    if "abc" in target.URI:
        DENY
    if target.SIP=="12" and target.DIP=="23" or target.SPORT==11:
        ALLOW
    submit()

def add_rule(x):
    t=Http()
    p=Policy()
    r=Rule()
    #r.add(t.SIP,"<","1.1.1.1",Effect.DENY)
    #r.add(TIME,"=","2013-01-01",Effect.DENY)
    s=["111","222"]
    r.add(t.USER,"!=","cloud")
    r.add(t.URI,"=","http://aaa.bbb.ccc")
    r.add(t.SIP,"<","1.1.1.1")
    r.add(t.TIME,">","2013-01-01")
    r.add(t.TIME,"in",s)
    r.ACTION="GET"
    r.EFFECT="ALLOW"
    r.TARGET="12345678"
    p.add(r)
    p.submit()
    pass

def add(attr,*args):
    t=inspect.stack()[-2][-2][0]
    attr=t[t.find("(")+1:t.find(")")]
    print attr


def submit():

	tree = ast.parse(inspect.getsource(rule))
	res = ast2xml().convert(tree)
	print >> open("res.xml","w"),prettify(res)
	pass

add_rule(1)